package cn.wolfcode.crm.service.impl;

import cn.wolfcode.crm.domain.Department;
import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.mapper.DepartmentMapper;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IDepartmentService;
import cn.wolfcode.crm.util.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class DepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    //保存和更新员工操作
    public int saveOrUpdate(Department record) {
        if (record.getId() == null) {
            return departmentMapper.insert(record);
        } else {
            return departmentMapper.updateByPrimaryKey(record);
        }
    }

    //查询单个员工操作
    public Department selectByPrimaryKey(Long id) {
        return departmentMapper.selectByPrimaryKey(id);
    }


    //员工列表操作
    public List<Department> selectAll() {
        return departmentMapper.selectAll();
    }

    public PageResult query(QueryObject qo) {
        int count = departmentMapper.queryCount(qo);
        if (count == 0) {
            return new PageResult(0, Collections.EMPTY_LIST);
        }
        List<Department> data = departmentMapper.queryList(qo);
        return new PageResult(count, data);
    }

    //改变部门的状态
    public void changeState(Long id) {
        departmentMapper.changeState(id);
    }

    public Boolean validateName(String sn, Long id) {
        //接受传入的部门编号
        Department dept = departmentMapper.validateName(sn);
        //如果dept找不到 用户名不存在   验证通过 返回true
        //如果前台传过来的id 和数据库查询到id相同 则是相同的用户 在做编辑操作的时候 验证也通过 返回true
        return  dept == null || dept.getId() == id;
    }

    @Override
    public Department selectByDepartmentName(String deptName) {
        return departmentMapper.selectByDepartmentName(deptName);
    }
}
